<script lang="ts" setup>
import { Button, CellGroup, Dialog, Field, showFailToast, showToast } from 'vant'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import QRCode from 'qrcode'
import { UserApi } from '~/api/UserApi'

// import Api from '~/api'

const env = import.meta.env
const REDIRECT_URI = `${location.origin}/login`
const APPID = env.VITE_appID

const route = useRoute()
const router = useRouter()

const username = ref('')
const password = ref('')

async function login() {
  const ok = await UserApi.login(username.value, password.value)
  if (ok) {
    showToast('登录成功')
    router.replace('/')
  }
  else {
    showFailToast('用户名或密码错误')
  }
}

async function wxAuth() {
  window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APPID}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=snsapi_userinfo&state=0#wechat_redirect`
}

onMounted(async () => {
  // 检测是否是登陆回来的
  console.log(route.query)
  const code = route.query.code
  if (code) {
    // 如果是wxAuth回来的，进行后端检验
    wxLogin(code as string)
  }
})

const year = computed(() => {
  const d = new Date()
  return d.getFullYear()
})

const canvasRef = ref(null as any)
const showQrcode = ref(false)

async function wxLogin(code: string) {
  const res = await UserApi.wxlogin(code)
  console.log('UserApi.wxlogin(code)')
  console.log(res)
  if (res.ok) {
    showToast('登录成功')
    router.replace('/')
  }
  else {
    showQrcode.value = true
    setTimeout(() => {
      console.log(canvasRef.value)

      QRCode.toCanvas(canvasRef.value, `wxId:${res.openid}`, (error) => {
        if (error) {
          console.error(error)
        }
        console.log('success!')
      })
      console.log('微信用户未经过认证')
    }, 50)
  }
}
</script>

<template>
  <div h-100vh w-full flex flex-col bg-light-3 p12 text-center>
    <Dialog
      v-model:show="showQrcode"
      title="登录失败"
    >
      <div my>
        微信用户未经过认证，请截图联系管理员
      </div>
      <canvas ref="canvasRef" width="120" height="120" />
    </Dialog>
    <img mt="20%" mx-auto block h-20 w-20 src="/icons/erp.png" alt="">
    <div mb>
      <div text-size-6>
        辽西塑业
      </div>
      <div text-size-3.5>
        企业事务在线管理系统
      </div>
    </div>

    <!-- autocomplete="on" -->
    <CellGroup inset mb>
      <Field v-model="username" placeholder="用户名" />
      <Field v-model="password" type="password" placeholder="密码" @keypress.enter="login" />
    </CellGroup>

    <CellGroup inset>
      <Button square type="primary" w-full @click="login">
        登录
      </Button>
    </CellGroup>

    <div mb2 mt-auto text-size-3 text-gray-3>
      使用其它方式登陆
    </div>

    <div flex justify-center>
      <div h10 w10 flex items-center justify-center b-rd-5 bg-green-5 @click="wxAuth">
        <FontAwesomeIcon :icon="['fab', 'weixin']" h-5 w-5 c="white" />
      </div>
    </div>

    <div mt text-size-3 text-gray-3>
      Copyright © 2018 - {{ year }} Lx Plastic Industry All Rights Reserved. 辽西塑业 版权所有
    </div>
  </div>
</template>

<route lang="yaml">
meta:
  layout: empty
</route>
